using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Roles;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Handler.Users.Roles
{
    /// <summary>
    /// 创建角色处理器
    /// </summary>
    public class CreateRoleHandler : IRequestHandler<CreateRoleCommand, APIResult<RoleDTO>>
    {
        private readonly IRepository<Rolemodel> roleRepository;

        public CreateRoleHandler(IRepository<Rolemodel> roleRepository)
        {
            this.roleRepository = roleRepository;
        }

        public async Task<APIResult<RoleDTO>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(request.RoleCode) ||
                string.IsNullOrWhiteSpace(request.RoleName))
            {
                return APIResult<RoleDTO>.Faile("角色编号和名称不能为空");
            }

            var code = request.RoleCode.Trim();
            var name = request.RoleName.Trim();

            // 检查角色编号是否已存在
            bool codeExists = await roleRepository.GetAll()
                .Where(r => r.IsDel == false && r.RoleCode == code)
                .AnyAsync();

            if (codeExists)
            {
                return APIResult<RoleDTO>.Faile("角色编号已存在");
            }

            // 创建角色
            var role = new Rolemodel
            {
                Id = YitIdHelper.NextId(),
                RoleCode = code,
                RoleName = name,
                Description = request.Description,
                Status = 1, // 默认启用
                RoleType = request.RoleType,
                Remark = request.Remark,
                //Createdate = DateTime.Now,
                //Createname = "系统管理员", // TODO: 从当前登录用户获取
                IsDel = false
            };

            int rows = await roleRepository.AddAsync(role);
            if (rows <= 0)
            {
                return APIResult<RoleDTO>.Faile("创建角色失败");
            }

            // 构造返回DTO
            var dto = new RoleDTO
            {
                Id = role.Id,
                RoleCode = role.RoleCode,
                RoleName = role.RoleName,
                Description = role.Description,
                Status = role.Status,
                RoleType = role.RoleType,
                Remark = role.Remark,
                //CreateDate = role.Createdate,
                //CreateName = role.Createname
            };

            return APIResult<RoleDTO>.Ok("创建角色成功", dto);
        }
    }
}
